package org.devocean.groupbuying.utils;

import java.util.Calendar;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DAOLogger {

	private final static Logger LOGGER = Logger.getLogger("DAO");

	@Before("execution(* org.devocean.groupbuying.dao.*.*(..))")
	public void before(JoinPoint joinPoint) {

		Object[] args = joinPoint.getArgs();
		String claz = joinPoint.getTarget().getClass().getSimpleName();
		String name = joinPoint.getSignature().getName();

		StringBuffer sb = new StringBuffer(claz + ".");
		sb.append(name + "(");

		for (int i = 0; i < args.length; i++) {
			Object o = args[i];
			sb.append("'" + o + "'");
			sb.append((i == args.length - 1) ? "" : ", ");
		}
		sb.append(")");
		sb.append(" executing ...");
		LOGGER.info(sb);
	}

	@Around("execution(* org.devocean.groupbuying.dao.*.*(..))")
	public Object arround(ProceedingJoinPoint joinPoint) throws Throwable {

		long start = Calendar.getInstance().getTimeInMillis();
		Object returnObject = joinPoint.proceed();
		Object[] args = joinPoint.getArgs();
		String claz = joinPoint.getTarget().getClass().getSimpleName();
		String name = joinPoint.getSignature().getName();

		StringBuffer sb = new StringBuffer(claz + ".");
		sb.append(name + "(");

		for (int i = 0; i < args.length; i++) {
			Object o = args[i];
			sb.append("'" + o + "'");
			sb.append((i == args.length - 1) ? "" : ", ");
		}
		sb.append(")");
		sb.append(" succussfuly executed in ");
		sb.append((Calendar.getInstance().getTimeInMillis() - start) + " ms");
		LOGGER.info(sb);

		return returnObject;
	}

	@AfterThrowing("execution(* org.devocean.groupbuying.dao.*.*(..))")
	public void efterThrow(JoinPoint joinPoint) throws Throwable {
		Object[] args = joinPoint.getArgs();
		String claz = joinPoint.getTarget().getClass().getSimpleName();
		String name = joinPoint.getSignature().getName();

		StringBuffer sb = new StringBuffer(claz + ".");
		sb.append(name + "(");

		for (int i = 0; i < args.length; i++) {
			Object o = args[i];
			sb.append("'" + o + "'");
			sb.append((i == args.length - 1) ? "" : ", ");
		}
		sb.append(")");
		sb.append(" threw an Exxception");
		LOGGER.error(sb);
	}

}
